added samples
[windows-sources.git] / sdk / samples / all in on code / Visual Studio 2010 / VBFTPUpload / MainForm.vb
blob4fa6359b232741cb8d341d6cbbc2519d9532295d
1 '*************************** Module Header ******************************'
2 ' Module Name: MainForm.vb
3 ' Project: VBFTPUpload
4 ' Copyright (c) Microsoft Corporation.
5 '
6 ' This is the main form of this application. It is used to initialize the UI and
7 ' handle the events.
8 '
9 ' This source is subject to the Microsoft Public License.
10 ' See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
11 ' All other rights reserved.
13 ' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
14 ' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
15 ' WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
16 '*************************************************************************'
18 Imports System.Linq
19 Imports System.Net
20 Imports System.Text
21 Imports System.IO
23 Partial Public Class MainForm
24 Inherits Form
26 Private _client As FTPClientManager = Nothing
28 Private _currentCredentials As NetworkCredential = Nothing
30 Public Sub New()
31 InitializeComponent()
33 RefreshUI()
34 End Sub
36 #Region "URL navigation"
38 ''' <summary>
39 ''' Handle the Click event of btnConnect.
40 ''' </summary>
41 Private Sub btnConnect_Click(ByVal sender As Object, ByVal e As EventArgs) _
42 Handles btnConnect.Click
44 ' Connect to server specified by tbFTPServer.Text.
45 Connect(Me.tbFTPServer.Text.Trim())
47 End Sub
49 Private Sub Connect(ByVal urlStr As String)
50 Try
51 Dim url As New Uri(urlStr)
53 ' The schema of url must be ftp.
54 If Not url.Scheme.Equals("ftp", StringComparison.OrdinalIgnoreCase) Then
55 Throw New ApplicationException("The schema of url must be ftp. ")
56 End If
58 ' Set the url to the folder that contains this file.
59 If url.IsFile Then
60 url = New Uri(url, "..")
61 End If
63 ' Show the Form UICredentialsProvider to get new Credentials.
64 Using provider As New UICredentialsProvider(Me._currentCredentials)
66 ' Show the Form UICredentialsProvider as a dialog.
67 Dim result = provider.ShowDialog()
69 ' If user typed the Credentials and pressed the "OK" button.
70 If result = System.Windows.Forms.DialogResult.OK Then
72 ' Reset the current Credentials.
73 Me._currentCredentials = provider.Credentials
75 Else
76 Return
77 End If
78 End Using
80 ' Initialize the FTPClient instance.
81 _client = New FTPClientManager(url, _currentCredentials)
83 AddHandler _client.UrlChanged, AddressOf client_UrlChanged
84 AddHandler _client.StatusChanged, AddressOf client_StatusChanged
85 AddHandler _client.ErrorOccurred, AddressOf client_ErrorOccurred
86 AddHandler _client.FileUploadCompleted, AddressOf client_FileUploadCompleted
87 AddHandler _client.NewMessageArrived, AddressOf client_NewMessageArrived
89 ' Refresh the UI and list the sub directories and files.
90 RefreshUI()
93 Catch webEx As System.Net.WebException
94 If (TryCast(webEx.Response, FtpWebResponse)).StatusCode = FtpStatusCode.NotLoggedIn Then
95 ' Reconnect the server.
96 Connect(urlStr)
98 Return
99 Else
100 MessageBox.Show(webEx.Message)
101 End If
102 Catch ex As Exception
103 MessageBox.Show(ex.Message)
104 End Try
105 End Sub
107 ''' <summary>
108 ''' Log the message of FTPClient.
109 ''' </summary>
110 Private Sub client_NewMessageArrived(ByVal sender As Object,
111 ByVal e As NewMessageEventArg)
112 Me.Invoke(New EventHandler(Of NewMessageEventArg)(
113 AddressOf client_NewMessageArrivedHandler), sender, e)
114 End Sub
116 Private Sub client_NewMessageArrivedHandler(ByVal sender As Object,
117 ByVal e As NewMessageEventArg)
118 Dim log As String = String.Format("{0} {1}", Date.Now, e.NewMessage)
119 Me.lstLog.Items.Add(log)
120 Me.lstLog.SelectedIndex = Me.lstLog.Items.Count - 1
121 End Sub
123 ''' <summary>
124 ''' Log the FileUploadCompleted event when a file was uploaded.
125 ''' </summary>
126 Private Sub client_FileUploadCompleted(ByVal sender As Object,
127 ByVal e As FileUploadCompletedEventArgs)
128 Me.Invoke(New EventHandler(Of FileUploadCompletedEventArgs)(
129 AddressOf client_FileUploadCompletedHandler), sender, e)
130 End Sub
132 Private Sub client_FileUploadCompletedHandler(ByVal sender As Object,
133 ByVal e As FileUploadCompletedEventArgs)
134 Dim log As String = String.Format(
135 "{0} Upload from {1} to {2} is completed. Length: {3}. ",
136 Date.Now, e.LocalFile.FullName, e.ServerPath, e.LocalFile.Length)
138 Me.lstLog.Items.Add(log)
139 Me.lstLog.SelectedIndex = Me.lstLog.Items.Count - 1
140 End Sub
142 ''' <summary>
143 ''' Log the ErrorOccurred event if there was an error.
144 ''' </summary>
145 Private Sub client_ErrorOccurred(ByVal sender As Object, ByVal e As ErrorEventArgs)
146 Me.Invoke(New EventHandler(Of ErrorEventArgs)(
147 AddressOf client_ErrorOccurredHandler), sender, e)
148 End Sub
150 Private Sub client_ErrorOccurredHandler(ByVal sender As Object, ByVal e As ErrorEventArgs)
151 Me.lstLog.Items.Add(String.Format("{0} {1} ", Date.Now, e.ErrorException.Message))
153 Dim innerException = e.ErrorException.InnerException
155 ' Log all the innerException.
156 Do While innerException IsNot Nothing
157 Me.lstLog.Items.Add(String.Format(vbTab & vbTab & vbTab & " {0} ",
158 innerException.Message))
159 innerException = innerException.InnerException
160 Loop
162 Me.lstLog.SelectedIndex = Me.lstLog.Items.Count - 1
163 End Sub
165 ''' <summary>
166 ''' Refresh the UI if the Status of the FTPClient changed.
167 ''' </summary>
168 Private Sub client_StatusChanged(ByVal sender As Object, ByVal e As EventArgs)
169 Me.Invoke(New EventHandler(AddressOf client_StatusChangedHandler), sender, e)
170 End Sub
172 Private Sub client_StatusChangedHandler(ByVal sender As Object, ByVal e As EventArgs)
173 RefreshUI()
175 Dim log As String = String.Format("{0} FTPClient status changed to {1}. ",
176 Date.Now, _client.Status.ToString())
178 Me.lstLog.Items.Add(log)
179 Me.lstLog.SelectedIndex = Me.lstLog.Items.Count - 1
180 End Sub
182 Private Sub RefreshUI()
183 ' Disable all the buttons if the client is uploading file.
184 If _client Is Nothing OrElse _client.Status <> FTPClientManagerStatus.Idle Then
186 btnBrowseLocalFolder.Enabled = False
187 btnUploadFolder.Enabled = False
189 btnBrowseLocalFile.Enabled = False
190 btnUploadFile.Enabled = False
192 btnDelete.Enabled = False
194 btnNavigateParentFolder.Enabled = False
195 lstFileExplorer.Enabled = False
196 Else
198 btnBrowseLocalFolder.Enabled = True
199 btnUploadFolder.Enabled = True
201 btnBrowseLocalFile.Enabled = True
202 btnUploadFile.Enabled = True
204 btnDelete.Enabled = True
206 btnNavigateParentFolder.Enabled = True
207 lstFileExplorer.Enabled = True
208 End If
210 btnConnect.Enabled = _client Is Nothing _
211 OrElse _client.Status = FTPClientManagerStatus.Idle
213 RefreshSubDirectoriesAndFiles()
215 End Sub
217 ''' <summary>
218 ''' Handle the UrlChanged event of the FTPClient.
219 ''' </summary>
220 Private Sub client_UrlChanged(ByVal sender As Object, ByVal e As EventArgs)
221 Me.Invoke(New EventHandler(AddressOf client_UrlChangedHandler), sender, e)
222 End Sub
224 Private Sub client_UrlChangedHandler(ByVal sender As Object, ByVal e As EventArgs)
225 RefreshSubDirectoriesAndFiles()
227 Dim log As String = String.Format("{0} The current url changed to {1}. ",
228 Date.Now, _client.Url)
230 Me.lstLog.Items.Add(log)
231 Me.lstLog.SelectedIndex = Me.lstLog.Items.Count - 1
232 End Sub
234 ''' <summary>
235 ''' Handle the DoubleClick event of lstFileExplorer.
236 ''' </summary>
237 Private Sub lstFileExplorer_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) _
238 Handles lstFileExplorer.DoubleClick
239 ' if only one item is selected and the item represents a folder, then navigate
240 ' to a subDirectory.
241 If lstFileExplorer.SelectedItems.Count = 1 _
242 AndAlso (TryCast(lstFileExplorer.SelectedItem, FTPFileSystem)).IsDirectory Then
243 Me._client.Naviagte((TryCast(lstFileExplorer.SelectedItem, FTPFileSystem)).Url)
244 End If
245 End Sub
247 ''' <summary>
248 ''' Handle the Click event of btnNavigateParentFolder.
249 ''' </summary>
250 ''' <param name="sender"></param>
251 ''' <param name="e"></param>
252 Private Sub btnNavigateParentFolder_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnNavigateParentFolder.Click
254 ' Navigate to the parent folder.
255 Me._client.NavigateParent()
256 End Sub
258 ''' <summary>
259 ''' List the sub directories and files.
260 ''' </summary>
261 Private Sub RefreshSubDirectoriesAndFiles()
262 If _client Is Nothing Then
263 Return
264 End If
266 lbCurrentUrl.Text = String.Format("Current Path: {0}", _client.Url)
268 Dim subDirs = _client.GetSubDirectoriesAndFiles()
270 ' Sort the list.
271 Dim orderedDirs = From dir In subDirs
272 Order By dir.IsDirectory Descending, dir.Name
273 Select dir
275 lstFileExplorer.Items.Clear()
276 For Each subdir In orderedDirs
277 lstFileExplorer.Items.Add(subdir)
278 Next subdir
279 End Sub
282 #End Region
284 #Region "Upload a Folder"
286 ''' <summary>
287 ''' Handle the Click event of btnBrowseLocalFolder.
288 ''' </summary>
289 Private Sub btnBrowseLocalFolder_Click(ByVal sender As Object, ByVal e As EventArgs) _
290 Handles btnBrowseLocalFolder.Click
291 BrowserLocalFolder()
292 End Sub
294 ''' <summary>
295 ''' Handle the Click event of btnUploadFolder.
296 ''' </summary>
297 Private Sub btnUploadFolder_Click(ByVal sender As Object, ByVal e As EventArgs) _
298 Handles btnUploadFolder.Click
300 ' If the tbLocalFolder.Text is empty, then show a FolderBrowserDialog.
301 If String.IsNullOrWhiteSpace(tbLocalFolder.Text) _
302 AndAlso BrowserLocalFolder() <> DialogResult.OK Then
303 Return
304 End If
307 Dim dir As New DirectoryInfo(tbLocalFolder.Text)
309 If Not dir.Exists Then
310 Throw New ApplicationException(
311 String.Format(" The folder {0} does not exist!", dir.FullName))
312 End If
314 ' Upload the selected items.
315 _client.UploadFolder(dir, _client.Url, chkCreateFolder.Checked)
316 Catch ex As Exception
317 MessageBox.Show(ex.Message)
318 End Try
319 End Sub
321 ''' <summary>
322 ''' Show a FolderBrowserDialog.
323 ''' </summary>
324 Private Function BrowserLocalFolder() As DialogResult
325 Using folderBrowser As New FolderBrowserDialog()
326 If Not String.IsNullOrWhiteSpace(tbLocalFolder.Text) Then
327 folderBrowser.SelectedPath = tbLocalFolder.Text
328 End If
329 Dim result = folderBrowser.ShowDialog()
330 If result = DialogResult.OK Then
331 tbLocalFolder.Text = folderBrowser.SelectedPath
332 End If
333 Return result
334 End Using
335 End Function
337 #End Region
339 #Region "Upload files"
341 Private Sub btnBrowseLocalFile_Click(ByVal sender As Object, ByVal e As EventArgs) _
342 Handles btnBrowseLocalFile.Click
343 BrowserLocalFiles()
344 End Sub
346 Private Sub btnUploadFile_Click(ByVal sender As Object, ByVal e As EventArgs) _
347 Handles btnUploadFile.Click
348 If tbLocalFile.Tag Is Nothing AndAlso BrowserLocalFiles() <> DialogResult.OK Then
349 Return
350 End If
353 Dim files As New List(Of FileInfo)()
354 Dim selectedFiles() As String = TryCast(tbLocalFile.Tag, String())
356 For Each selectedFile In selectedFiles
357 Dim fileInfo_Renamed As New FileInfo(selectedFile)
358 If Not fileInfo_Renamed.Exists Then
359 Throw New ApplicationException(
360 String.Format(" The file {0} does not exist!", selectedFile))
361 Else
362 files.Add(fileInfo_Renamed)
363 End If
364 Next selectedFile
366 If files.Count > 0 Then
367 _client.UploadFoldersAndFiles(files, _client.Url)
368 End If
369 Catch ex As Exception
370 MessageBox.Show(ex.Message)
371 End Try
372 End Sub
374 ''' <summary>
375 ''' Show a FolderBrowserDialog.
376 ''' </summary>
377 Private Function BrowserLocalFiles() As DialogResult
378 Using fileBrowser As New OpenFileDialog()
379 fileBrowser.Multiselect = True
380 Dim result = fileBrowser.ShowDialog()
381 If result = DialogResult.OK Then
382 tbLocalFile.Tag = fileBrowser.FileNames
384 Dim filesText As New StringBuilder()
385 For Each file In fileBrowser.FileNames
386 filesText.Append(file & ";")
387 Next file
388 tbLocalFile.Text = filesText.ToString()
389 End If
390 Return result
391 End Using
392 End Function
395 #End Region
397 #Region "Delete files"
399 Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs) _
400 Handles btnDelete.Click
401 If lstFileExplorer.SelectedItems.Count = 0 Then
402 MessageBox.Show("Please select the items to delete in the FTP File Explorer")
403 End If
405 Dim itemsToDelete =
406 lstFileExplorer.SelectedItems.Cast(Of FTPFileSystem)().ToList()
408 Me._client.DeleteItemsOnFTPServer(itemsToDelete)
410 RefreshUI()
411 End Sub
413 #End Region
415 End Class